﻿using System.Web.Mvc;
using Joz.Web.Models;
using Newtonsoft.Json;
using Face.BLL;
using System;
using System.Web;
using System.IO;
using Common.Unit;
using Face.Model;

namespace Joz.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //检测是否有faceset，无则建立
            var setModel = FaceSet_Bll.Instance.GetModel("");
            if (setModel == null)
            {
                string MyFirstFace = "MyFirstFace";
                string json = FaceSetHelper.CreateFaceSet(MyFirstFace);
                dynamic D = JsonConvert.DeserializeObject<dynamic>(json);
                if (D.faceset_token != null)
                {
                    FaceSet_Bll.Instance.Add(new Face.Model.FaceSet_Model()
                    {
                        FaceSetName = MyFirstFace,
                        FaceSetToken = D.faceset_token
                    });
                }
            }
            return View();
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Face(string key, int pid = 1)
        {
            int totalCount = 0;
            string where = string.Empty;
            if (key.IsNotEmptyNotNull())
                where += string.Format(" userName like '%{0}%'", key.Trim());
            var result = Users_Bll.Instance.GetModelList(ref totalCount, where, "", "addtime desc", 15, pid);
            ViewBag.totalCount = totalCount;
            ViewBag.key = key;
            return View(result);
        }
        /// <summary>
        /// 录入人脸资料
        /// </summary>
        /// <returns></returns>
        public ActionResult AddFace()
        {
            return View();
        }
        /// <summary>
        /// 从数据库中搜索
        /// </summary>
        /// <returns></returns>
        public ActionResult SearchFace()
        {
            return View();
        }

        #region 删除数据操作

        public JsonResult DeleteUser(int userId)
        {
            try
            {
                var userModel = Users_Bll.Instance.GetModelByID(userId);
                if (userModel == null) throw new Exception("未找到该用户信息");
                string fileUrl = Server.MapPath("\\Upfiles\\heads\\" + userModel.UserImg);
                //删除用户信息
                Users_Bll.Instance.DeleteUser(userModel.Id.Value);
                //删除关联文件
                if (System.IO.File.Exists(fileUrl))
                {
                    System.IO.File.Delete(fileUrl);
                }
                //删除当前图片的集合
                var setModel = FaceSet_Bll.Instance.GetModel("");
                FaceSetHelper.DeleteFace_Token(setModel.FaceSetToken, userModel.UserToken);

                return Json("true");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        #endregion

        #region 上传文件操作

        public JsonResult UploadFile(HttpPostedFileBase file)
        {
            try
            {
                string username = Request["username"].ToString();
                if (username.IsEmptyOrNull()) throw new Exception("姓名不能为空");
                if (file == null) throw new Exception("上传文件为空");
                string fileExt = Path.GetExtension(file.FileName);
                BinaryReader binReader = new BinaryReader(file.InputStream);
                byte[] buffer = binReader.ReadBytes(file.ContentLength);
                string savePath = Server.MapPath("\\Upfiles\\heads\\");
                string saveName = Guid.NewGuid() + fileExt;

                CommonCmdResult cmd = new HeadPhotoHelper().HeadPhotoPSUseFacePlusPlus(buffer, file.FileName, fileExt, string.Empty);
                if (!cmd.Flag) { throw new Exception(cmd.Msg); }


                if (!Directory.Exists(savePath))
                    Directory.CreateDirectory(savePath);
                System.Drawing.Image img = (System.Drawing.Bitmap)cmd.Obj;
                img.Save(savePath + saveName);

                string face_token = cmd.Msg;
                int result = Users_Bll.Instance.Add(new Users_Model()
                {
                    AddTime = DateTime.Now,
                    UserImg = saveName,
                    UserName = username,
                    UserToken = face_token
                });
                if (result > 0)
                {
                    var setModel = FaceSet_Bll.Instance.GetModel("");
                    //添加到集合中
                    FaceSetHelper.AddFace_Token(setModel.FaceSetToken, face_token);
                }
                return Json(result > 0 ? true : false);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        #endregion



        #region 人脸识别操作

        public JsonResult SearchFile(HttpPostedFileBase file)
        {
            try
            {
                string faceToken = string.Empty;
                if (file == null) throw new Exception("上传文件为空");
                string fileExt = Path.GetExtension(file.FileName);
                BinaryReader binReader = new BinaryReader(file.InputStream);
                byte[] buffer = binReader.ReadBytes(file.ContentLength);
                //人脸识别
                string json = FaceHelper.FacePlusPlusGetFaceInfo(buffer, file.FileName, fileExt);
                //解析json数据
                dynamic D = JsonConvert.DeserializeObject<dynamic>(json);
                if (D.faces != null && D.faces.Count > 0)
                {
                    if (D.faces.Count > 1) throw new Exception("请不要上传多人合照！");

                    string face_token = D.faces[0].face_token;
                    //从数据中获取相应的faceset集合token
                    var setModel = FaceSet_Bll.Instance.GetModel("");
                    //从现有的集合人脸中，识别最相近的一组
                    string compare = FaceHelper.SearchFaceSetInfo(face_token, setModel.FaceSetToken);
                    //解析比较结果
                    dynamic F = JsonConvert.DeserializeObject<dynamic>(compare);
                    //获得相似度最高的一组face_token，从数据库查询该用户信息
                    if (F.results != null && F.results.Count > 0)
                    {
                        if (F.results[0].confidence > 85)
                            faceToken = F.results[0].face_token;
                    }
                }
                Users_Model faceModel = new Users_Model();
                if (faceToken.IsNotEmptyNotNull())
                    faceModel = Users_Bll.Instance.GetModel("userToken=@userToken", new System.Data.SqlClient.SqlParameter("@userToken", faceToken));

                if (faceModel != null && faceModel.Id != null)
                    return Json(faceModel.UserName + "+" + faceModel.AddTime.Value.ToString("yyyy-MM-dd HH:mm") + "+" + faceModel.UserImg);
                else
                    return Json("false");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        #endregion
    }
}